<template>
  <div class="edit-screen">
    <design-header
      @open-insert-drawer="handleInsert"
      @delete-one-compo="handleDeleteOneCompo"
      @update-page-config="handleUpdatePageConfig"
    >
    </design-header>

    <!-- 插入组件抽屉 -->
    <div class="aside-drawer" v-show="insertDrawer">
      <div class="title">
        <h3>插入</h3>
        <img
          @click="insertDrawer = false"
          src="@/assets/image/delete.png"
          alt="删除"
        />
      </div>
      <design-insert @on-dragstart="handleDragOneToCanvas" />
    </div>

    <!-- 画布区域 -->
    <!-- {{ pageConfig.list }} -->
    <!-- 111-- {{ pageConfig }} -->
    <div class="canvas-area">
      <!-- <el-scrollbar height="100%"> -->
      <div class="workbench-container" @dragover.prevent @drop="onDrop">
        <!-- <vue-ruler-tool class="vue-ruler" :step-length="50" :parent="true" :is-scale-revise="true" @input="handleInputPresetLine" :value="presetLine"> -->
        <!-- 对齐线 -->
        <div
          class="workbench"
          :style="{
            'background-image': `url(${pageConfig?.bgImgUrl})`,
            width: `${pageConfig?.w / 100}rem`,
            height: `${pageConfig?.h / 100}rem`
          }"
        >
          <div v-if="!pageConfig?.list?.length" class="empty-notice-area">
            <p>还未添加任何组件，点击插入进行添加</p>
          </div>
          <DraggableContainer v-else>
            <child-item :asideChildren="pageConfig?.list"></child-item>
          </DraggableContainer>
        </div>
        <!-- </vue-ruler-tool> -->
      </div>
      <!-- </el-scrollbar> -->
    </div>
  </div>
</template>

<script>
import Vue3DraggableResizable from 'vue3-draggable-resizable';
import { DraggableContainer } from 'vue3-draggable-resizable';
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css';

import DesignInsert from './design-insert';

import VueRulerTool from './component/vue-ruler-tool/src/components/vue-ruler-tool.vue';

import DesignHeader from './design-header.vue';
import { ref, reactive, toRefs, onMounted, onBeforeMount, computed } from 'vue';
import ChildItem from './child-item.vue';
// import { Vue3RulerTool } from 'vue3-ruler-tool';
// import 'vue3-ruler-tool/dist/style.css';
import useComponentConfig from '@/views/design-center/store/component-config';

import { getIdAndDeleteIt } from '@/utils/common';
import { getScreenAndReportDetailApi } from '@/views/design-center/api/screen';

import { useRoute } from 'vue-router';

import { useMousePosition } from '@/hooks/use-mouse-position.js';

export default {
  components: {
    DesignHeader,
    DesignInsert,
    VueRulerTool,
    ChildItem,
    // Vue3RulerTool,
    DraggableContainer,
    Vue3DraggableResizable
  },
  setup() {
    const event = ref(useMousePosition());
    const workNode = computed(() => {
      return document.querySelector('.workbench-container').getClientRects();
    });

    const route = useRoute();
    // 拖拽缩放功能
    const widgetX = ref(0); //差值
    const widgetY = ref(0);
    const ruleX = ref(18); //差值
    const ruleY = ref(18); //差值
    const currentWidget = ref({});
    const currentComponents = ref({});
    // const active = ref(false); //当前组件是否高亮

    const insertDrawer = ref(false); //是否展示插入组件抽屉

    const useComponentConfigStore = useComponentConfig();
    const { pageConfig, currentCompoId, checkMoreCompoList } = toRefs(
      useComponentConfigStore
    );
    // console.log('route.query.reportName', route.query.reportName);

    // pageConfig.value.name = route.query.reportName;

    //打开插入组件侧边栏
    const handleInsert = () => {
      insertDrawer.value = true;
    };

    /**
     * @description: 拖拽组件开始
     * @param {*} e
     * @param {*} widget
     * @return {*}
     */
    const handleDragOneToCanvas = (e, widget) => {
      widgetX.value = e.offsetX;
      widgetY.value = e.offsetY;
      // console.log('拖拽进来了组件', e, widget);
      let getSingKeyObj = {};

      Object.entries(widget).map(([key, value]) => {
        if (!(Object.prototype.toString.call(value) === '[object Object]')) {
          getSingKeyObj[key] = value;
        }
      });

      let setups = widget?.options?.setups?.reduce((pre, next) => {
        pre[next['name']] = next['value'];
        return pre;
      }, {});
      // let data = widget.options.data.reduce((pre, next) => {
      //     pre[next['name']] = next['value'];
      //     return pre;
      // }, {});
      // let events = widget.options.events.reduce((pre, next) => {
      //     pre[next['name']] = next['value'];
      //     return pre;
      // }, {});

      let componentStyles = widget?.options?.styles;
      componentStyles = Array.isArray(componentStyles)
        ? componentStyles
        : Object.values(componentStyles);

      componentStyles = componentStyles.flat();

      //处理配置项的子集
      let a = componentStyles.reduce((pre, next) => {
        console.log('de------------', next?.children);

        if (!!next?.children?.length) {
          // return Object.assign({}, item, { ...item.children });
          pre.push([next, next.children]);
        } else {
          // return item;
          pre.push(next);
        }
        return pre;
      }, []);

      componentStyles = a.flat().flat();
      console.log(componentStyles, 55555555555);

      let styles = componentStyles.reduce((pre, next) => {
        pre[next['name']] = next['value'];
        return pre;
      }, {});
      console.log(styles, 568989899899);
      currentWidget.value = {
        ...getSingKeyObj,
        setups,
        styles
        // options: widget.options //临时注释掉的
      };
    };
    /**
     * @description: 从抽屉拖拽组件到画布结束
     * @param {*} e
     * @return {*}
     */
    const onDrop = (e) => {
      let id = `key${Date.now()}`;
      let x = e.offsetX - widgetX.value;
      let y = e.offsetY - widgetY.value;
      let componentNum = useComponentConfigStore.pageConfig?.list
        ?.map((item) => item.type)
        .reduce((pre, next) => {
          pre[next] ? pre[next]++ : (pre[next] = 1);
          return pre;
        }, {});
      useComponentConfigStore.pageConfig?.list?.push({
        id: id,
        show: true, //组件是否展示
        lock: false, //组件是否锁定
        fartherLock: false, //父组件是否锁定-用于父组件锁定后子组件递归锁定
        linkageStatus: true, //联动改组件初始值即为联动状态,可以在全局联动位置解除联动关系
        ...currentWidget.value,
        setups: {
          ...currentWidget.value.setups,
          componentName: `${currentWidget?.value.setups?.componentName}${
            componentNum[currentWidget.value.type] + 1 || 1
          }`
        },
        styles: {
          ...currentWidget.value.styles,
          x: x - ruleX.value,
          y: y - ruleY.value
        }
      });
      currentCompoId.value = id;
      console.log(useComponentConfigStore.pageConfig?.list, '拖拽结束后的list');
    };
    /**
     * @description:组件在画布中拖拽
     * @param {*} x
     * @param {*} y
     * @param {*} index
     * @return {*}
     */

    /**
     * @description:组件的放大缩小
     * @param {*} x
     * @param {*} y
     * @param {*} w
     * @param {*} h
     * @param {*} index
     * @return {*}
     */

    const print = (val) => {
      // console.log(val);
    };

    /**
     * @description:删除画布中配置的组件
     * @return {*}
     */
    const handleDeleteOneCompo = () => {
      console.log('来了吗-', currentCompoId.value);
      pageConfig.value.list = getIdAndDeleteIt(
        pageConfig.value.list,
        currentCompoId.value
      );
      // useComponentConfigStore.pageConfig.list = useComponentConfigStore.pageConfig.list?.filter((item) => item.id !== activeId.value);
    };

    const handleUpdatePageConfig = (value) => {
      useComponentConfigStore.pageConfig.bgImgUrl = value;
    };

    let presetLine = ref([
      // { type: 'h', site: 200 },
      // { type: 'v', site: 100 }
    ]);
    const handleInputPresetLine = (list) => {
      presetLine.value = list;
    };

    const INIT = {
      bigScreenName: route.query.bigScreenName,
      w: '1920',
      h: '1080',
      bgImgUrl: '',
      list: []
    };

    //获取大屏配置详情
    const getScreenAndReportDetail = async () => {
      let res = await getScreenAndReportDetailApi({
        bigScreenId: route.query.bigScreenId
      });
      // console.log('获取大屏配置的详情', JSON.parse(res.data), pageConfig.value);
      if (res.code === 200 && res.data) {
        const configStr = res.data.configStr;
        pageConfig.value = configStr
          ? JSON.parse(configStr)
          : {
              ...INIT
            };

        useComponentConfigStore.setPageConfig(pageConfig.value);
        return false;
      }
      //值初始化
      pageConfig.value = {
        ...INIT
      };
    };
    getScreenAndReportDetail();

    // window.onbeforeunload = function (e) {
    //     console.log('beforeunload');
    //     return 1;
    // };

    return {
      event,
      presetLine,
      handleInputPresetLine,
      insertDrawer,
      ruleX,
      ruleY,
      widgetX,
      widgetY,
      // active,
      currentWidget,
      currentComponents,

      pageConfig,
      getScreenAndReportDetail,
      print,
      handleInsert,
      handleDragOneToCanvas,
      onDrop,
      handleDeleteOneCompo,
      handleUpdatePageConfig,
      useComponentConfigStore
    };
    // watch(
    //   () => event.ctrlKey,
    //   (newValue, oldValue) => {
    //     console.log("newValue", newValue, "oldvalue", oldValue);
    //   }
    // );
  },
  watch: {
    'event.ctrlKey'(nv) {
      if (nv === false) {
        this.useComponentConfigStore.checkMoreCompoList = [];
      }
    }
  }
};
</script>
<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

// .close-icon {
//     position: absolute;
//     width: 0.4rem;
//     height: 0.4rem;
//     background: #165dff;
//     box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.1);
//     border-radius: 6px 0px 0px 6px;
//     display: flex;
//     justify-content: center;
//     align-items: center;
//     color: #fff;
//     top: 0.88rem;
//     left: -0.4rem;
// }
.edit-screen {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.aside-drawer {
  background: #ffffff;
  box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.1);
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  width: 6.4rem;
  z-index: 1100;

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 0.16rem;
    padding: 0.12rem 0.24rem;
    font-weight: 600;
    border-bottom: 0.01rem solid #ccc;
    margin-bottom: 0.16rem;
  }
}

.canvas-area {
  padding: 0 1.2rem;
  width: 100%;
  height: 100%;
  //   height: calc(100vh - 0.8rem);
  // overflow-y: auto;

  .workbench-container {
    position: relative;
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    border-left: 0.01rem solid #e5e6eb;
    border-right: 0.01rem solid #e5e6eb;
    overflow-x: auto;
    /* overflow-y: hidden; */

    .empty-notice-area {
      display: flex;
      width: 100%;
      height: 100%;
      justify-content: center;
      align-items: center;
      position: absolute;
      left: 0%;
      top: 0%;
    }
  }

  .vue-ruler {
    width: 100% !important;
    // padding: 18px 0px 0px 18px;
  }

  .workbench {
    height: 100%;
    // background-color: #1e1e1e;
    background-color: transparent;
    position: relative;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
    margin: 0;
    padding: 0;
    background-position: 0% 0%;
    background-size: 100% 100%;
    background-repeat: initial;
    background-attachment: initial;
    background-origin: initial;
    background-clip: initial;
  }
}

:deep(.el-drawer__title) {
  font-size: 0.16rem;
}

// .vdr-container {
//     box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
//     // border: 0.01rem solid green;
//     // background: #fff;
//     background: transparent;
//     &:hover {
//         cursor: move;
//     }
// }
// // .vdr-handle {
// //     display: block !important;
// //     width: 4px;
// //     height: 4px;
// //     border: 1px solid #ccc;
// // }
// .vdr-container.active {
//     // border-color: #fff;
//     border-style: none;
//     border: none;
// }
</style>
